import { _decorator, Node, Component, Label } from "cc";
import { XUtils } from "../comm/XUtils";
import NativeHelper from "../comm/NativeHelper";
import ADCtrl from "../ctrl/ADCtrl";
import { EventReport, ReportDataAdClick } from "../net/EventReport";
import UserModel from "../data/UserModel";
import { EnvType } from "../data/GameConfig";
import { GameConfig } from "../data/GameConfig";

const { ccclass, property } = _decorator;

@ccclass('BtnAd')
export class BtnAd extends Component {
    @property(Label)
    private lbMultiple: Label = null;

    private _multiple: number = 1;
    private _adCallback: (isSuccess: boolean) => void = null;
    private _data: ReportDataAdClick = null;

    protected start(): void {
    }

    private onBtnClick() {
        // 播放广告
        if (this._adCallback) {
            BtnAd.playAd(this._data).then(isSuccess => {
                this._adCallback(isSuccess);
            });
        }
    }

    public setMultiple(multiple: number) {
        this._multiple = multiple;
        this.lbMultiple.string = `X${multiple}`;
    }

    public getMultiple() {
        return this._multiple;
    }

    public setAdCallback(callback: (isSuccess: boolean) => void, data: ReportDataAdClick) {
        XUtils.bindButton(this.node, this.onBtnClick, this);
        this._adCallback = callback;
        this._data = data;
        EventReport.ad_show({
            adpos: data.adpos,
            level: UserModel.curLevelId,
        });
    }

    public static playAd(data: ReportDataAdClick) {
        if (data) {
            ADCtrl.instance.lastClickAdPos = data.adpos;
            EventReport.adClick(data);
        }
        // 播放广告
        return new Promise<boolean>((resolve, reject) => {
            // 播放广告 代码xxxx
            NativeHelper.onceAdRewardedCallback((bSuccess: boolean) => {
                resolve(bSuccess);
                if (bSuccess) {
                    ADCtrl.instance.onAdRewarded();
                }
            });
            NativeHelper.callShowAdRewarded({
                placement: {
                    adPos: data.adpos,
                },
                customData: {
                    level: UserModel.curLevelId,
                    version: GameConfig.version,
                    isTest: GameConfig.envType == EnvType.Test,
                    adPos: data.adpos,
                },
                changeAdType: ADCtrl.instance.needChangeAdType
            });
        });
    }
}
